package th.retrofit.lib;

import java.util.LinkedList;
import java.util.List;

/**
 * https://leetcode-cn.com/problems/spiral-matrix/
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 */
public class Solution54 {

    // 一层一层遍历
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> results = new LinkedList<>();
        int m = matrix.length;;
        int n = matrix[0].length;
        int limit = Math.min((m + 1) / 2, (n + 1) / 2);
        int[][] directions = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int idx = 0;
        for (int i = 0; i < limit; i++) {
            idx = 0;
            int rowNum = m - 2 * i;
            int colNum = n - 2 * i;
            int total = 0;
            if (rowNum < 2) {
                total = colNum;
            } else {
                total = colNum < 2 ? rowNum : 2 * (colNum + rowNum - 2);
            }
            int x = i, y = i;
            for (int j = 0; j < total; j++) {
                results.add(matrix[x][y]);
                if (x + directions[idx][0] < i || x + directions[idx][0] >= m - i
                        || y + directions[idx][1] < i || y + directions[idx][1] >= n - i) {
                    idx++;
                }
                if (idx < 4) {
                    x += directions[idx][0];
                    y += directions[idx][1];
                }
            }
        }
        return results;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        List<Integer> results = new Solution54().spiralOrder(matrix);
        for (int i = 0; i < results.size(); i++) {
            System.out.print(results.get(i));
            if (i != results.size() - 1) {
                System.out.print(", ");
            } else {
                System.out.println();
            }
        }
    }
}
